package tools;

import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;

/**
 * Author: 4ut15m.4ny0neSec
 * Date: 2022/1/10
 * Desc: 工具类
 */
public class Tool {

    /**
     * 功能：版本号比较
     * 返回值：负数（你的版本小于目标版本）、0 （两者相等）、正数（你的版本大于目标版本）
     */
    public static int compareVersion(String yourversion, String targetVersion) {
        if (yourversion == null || targetVersion == null) {
            try {
                throw new Exception("compareVersion error:illegal params.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String[] versionArray1 = yourversion.split("\\.");
        String[] versionArray2 = targetVersion.split("\\.");
        int idx = 0;
        int minLength = Math.min(versionArray1.length, versionArray2.length);//取最小长度值
        int diff = 0;
        while (idx < minLength
                && (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0//先比较长度
                && (diff = versionArray1[idx].compareTo(versionArray2[idx])) == 0) {//再比较字符
            ++idx;
        }
        //如果已经分出大小，则直接返回，如果未分出大小，则再比较位数，有子版本的为大；
        diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length;
        return diff;
    }

    /**
     * 发起post请求
     */
    public static String Post(String url, String[] params) {
        URLConnection urlConnection = null;
        URL u = null;
        InputStream ios = null;
        String res = "";
        PrintWriter out = null;
        String param = "";
        if (params.length > 1) {
            for (String s : params) {
                param += s + "&";
            }
        } else {
            param = params[0];
        }

        try {
            u = new URL(url);
            urlConnection = u.openConnection();

            urlConnection.setRequestProperty("accept", "*/*");
            urlConnection.setRequestProperty("connection", "Keep-Alive");
            urlConnection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);

            out = new PrintWriter(urlConnection.getOutputStream());
            out.print(param);
            out.flush();

            ios = urlConnection.getInputStream();
            return getRes(ios);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将响应流的内容转化为字符串
     */
    public static String getRes(InputStream inputStream) {
        try {
            return IOUtils.toString(inputStream, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
